<template>
    <div ref="container">
        <div
            class="flex-col-start moviesTribe"
            v-if="!pageData.id && pageData.pageTitle">
            <!-- header -->
            <header
                class="banner_container"
                ref="pageDom">
                <!-- banner图片 -->
                <van-image
                    class="banner"
                    fit="cover"
                    :src="pageData?.pageHeaderImage">
                    <template #loading>
                        <div class="flex-center loading_bg">
                            测试页面
                            <!-- <van-loading
                                type="spinner"
                                size="20" /> -->
                        </div>
                    </template>
                    <!-- <template #error>
                        <van-image
                            class="banner"
                            src="https://cdn.kumiamei.com/web/test/img_fail_banner-bdf5e8c3c.jpg"
                    /></template> -->
                </van-image>
                <!-- 遮罩层 -->
                <div class="mask">
                    <!-- 返回、分享 -->
                    <div class="flex flex-between top_icon">
                        <van-icon
                            name="arrow-left"
                            color="#fff"
                            v-if="!isShare"
                            @click="closeWebView"
                            size="20" />
                        <van-icon
                            name="share-o"
                            color="#fff"
                            v-if="!isShare"
                            @click="handleShare"
                            size="20" />
                    </div>
                    <!-- 标题 -->
                    <div class="title">
                        <div class="title_text">{{ pageData?.pageTitle || '' }}</div>
                    </div>
                    <!-- 副标题 -->
                    <div class="pageSubtitle">
                        {{ pageData?.pageSubtitle || '' }}
                    </div>
                </div>
            </header>
            <!-- body -->
            <section class="flex flex-wrap flex-between section_container">
                <CardItem
                    @onJumpApp="onJumpApp"
                    v-for="(sourceItem, index) in pageData?.pageResource"
                    :resourcePoster="sourceItem?.resourcePoster"
                    :resourceName="sourceItem?.resourceName"
                    :resourceLabel="sourceItem?.resourceLabel"
                    :score="sourceItem?.score"
                    :tribeId="sourceItem?.tribeId"
                    :clubDisPlayId="sourceItem?.clubDisPlayId"
                    :channelDisPlayId="sourceItem?.channelDisPlayId"
                    :channelId="sourceItem?.channelId || ''"
                    :messageTime="sourceItem?.msgTime || ''"
                    :msgUID="sourceItem?.msgUID"
                    :key="index" />
            </section>

            <div
                class="more_recommend"
                v-if="pageData.historyCollection.length !== 0">
                {{ t('moviesTribe.MoreRecommendations') }}
            </div>
            <!-- history -->
            <section class="flex flex-wrap flex-between history_container">
                <HistoryCard
                    v-for="(history, index) in pageData?.historyCollection"
                    :key="index"
                    :pageH5Url="history.pageH5Url || ''"
                    :pageResource="history.pageResource || []"
                    :pageTitle="history.pageTitle || ''"
                    @on-jump-link="onJumpLink" />
            </section>
            <!-- btn -->
            <div
                class="flex-center jump_btn"
                v-if="!isInIframe"
                @click="goChannel(10)">
                {{ t('moviesTribe.WatchMoreInChannel') }}
            </div>
        </div>
        <Empty v-else />
    </div>
</template>
<script setup lang="ts">
    // 获取iframe嵌套的子页面的高度
    import { onMounted, ref, reactive, nextTick } from 'vue';
    import { useI18n } from 'vue-i18n';
    import { useQuery } from '@utils/useRouters';
    import { showToast } from 'vant';
    import {
        reportEvent,
        closeWebview,
        openSharePanel,
        getAppEnvironment,
        routeAppView,
    } from '@/utils/NativeUtils';
    import { useRouter } from 'vue-router';
    import { isIOS } from '@/utils/common';
    import { getIndexData, getShareData } from './requests';

    import CardItem from './components/CardItem.vue';
    import HistoryCard from './components/HistoryCard.vue';
    import Empty from './components/Empty.vue';
    import type { IShareConfig, IPageData } from './types';

    const router = useRouter();
    const { t } = useI18n();

    const props = withDefaults(
        defineProps<{
            isShare?: boolean;
        }>(),
        {
            isShare: false,
        }
    );
    const pageDom = ref(null);

    const container = ref(null);
    const isInIframe = ref(false);
    const isAppProd = ref(null);
    const redirectUrl = ref('');
    const timer = ref(null);
    const shareConfig = reactive<IShareConfig>({
        channelId: '',
        channelDisplayId: '',
        clubId: '',
        clubDisplayId: '',
    });
    const pageData = reactive<IPageData>({
        id: ' ',
        pageTitle: ' ',
        pageSubtitle: '',
        pageHeaderImage: '',
        pageResource: [],
        historicalLinks: [],
        historyCollection: [],
        channelDisPlayId: '',
    });
    const sharePageId = ref(null);
    // const lang = ['en', 'ar', 'ur', 'tr', ' in'].includes(window.sessionStorage.getItem('language'))
    //     ? window.sessionStorage.getItem('language')
    //     : 'en';
    function getPageData(id: string) {
        getIndexData(id)
            .then((data) => {
                Object.assign(pageData, data);
                shareConfig.channelId = data?.pageResource[0]?.channelId || '';
                shareConfig.channelDisplayId = data.channelDisPlayId || '';
                shareConfig.clubId = data?.pageResource[0]?.tribeId || '';
                shareConfig.clubDisplayId = data?.pageResource[0]?.clubDisPlayId || '';
                nextTick(() => {
                    handleBack();
                });
            })
            .catch(() => {
                pageData.id = '';
                pageData.pageTitle = '';
            });
    }
    // 点击跳转频道IM
    function goChannel(countdown = 10) {
        // 如果是分享页面，就跳转深链
        if (props.isShare) {
            const url = `https://Kumianmei.go.link/home/web?url=${window.location.origin}/movies-tribe?id=${sharePageId.value}&windowType=FULL_MODE&urlType=1&adj_t=9ykknhp`;
            if (isIOS) {
                window.location.href = url;
            } else {
                window.open(url);
            }
            // 深链为空
            if (!redirectUrl.value && isIOS) {
                clearTimeout(timer.value);
                timer.value = setTimeout(() => {
                    window.location.href = 'https://itunes.apple.com/cn/app/id1509626067';
                }, countdown * 1000);
            } else {
                timer.value = setTimeout(() => {
                    window.location.href =
                        'https://play.google.com/store/apps/details?id=com.kumiamei.Kumianmei';
                }, countdown * 1000);
            }
            reportEvent('影视部落', '点击事件', `影视部落分享页`);
        } else {
            const {
                channelId = '',
                clubId = '',
                clubDisplayId = '',
                channelDisplayId = '',
            } = shareConfig;
            reportEvent('影视部落', '点击事件', `跳转频道channelId：${channelId}`);
            routeAppView(
                `Kumianmei://App/ClubChannel?clubId=${clubId}&clubDisplayId=${clubDisplayId}&channelId=${channelId}&channelDisplayId=${channelDisplayId}`
            );
        }
    }
    // 跳转频道
    function onJumpApp({ clubId, clubDisplayId, channelId, channelDisplayId, msgId, messageTime }) {
        // 分享页不执行下边逻辑
        if (props.isShare) {
            return;
        }
        if (!clubId || !clubDisplayId || !channelId || !channelDisplayId || !msgId) {
            return;
        }
        reportEvent('影视部落', '点击事件', `跳转频道页消息channelId：${channelId}`);

        routeAppView(
            `Kumianmei://App/ClubChannel?clubId=${clubId}&clubDisplayId=${clubDisplayId}&channelId=${channelId}&channelDisplayId=${channelDisplayId}&msgId=${msgId}&messageTime=${messageTime}`
        );
    }
    // 跳转h5页面
    function onJumpLink(link) {
        // 分享页不执行下边逻辑
        if (props.isShare || !link) {
            return;
        }
        // if (!link) {
        // return showToast(t('无跳转链接'));
        // }
        const url = `Kumianmei://Web/FULL_MODE?url=${link}`;
        reportEvent('影视部落', '点击事件', `跳转历史${link}`);
        routeAppView(url);
    }
    // 判断端内端外
    function isAppProduction() {
        const onError = () => {
            // 错误处理
            isAppProd.value = false;
        };
        getAppEnvironment(
            useQuery(),
            () => {
                isAppProd.value = true;
            },
            onError
        );
        // .then((env) => {
        //     if (env.toString().toUpperCase() === 'Kumianmei') {
        //         // 正常处理
        //         console.log('正常处理');
        //     } else {
        //         onError();
        //     }
        // })
        // .catch(onError);
    }
    // isAppProduction();
    // 点击分享按钮
    function handleShare() {
        const { id = '', pageHeaderImage = '', pageTitle = '', pageSubtitle = '' } = pageData;
        // if (!id) {
        //     // pageId不能为空
        //     return showToast(t('common.ShareFailed'));
        // }
        openSharePanel(
            'MOVIES_TRIBE_H5', // 活动类型
            'FULL_MODE', // 窗口模式
            `${window.location.origin}/movies-tribe?id=${id}`, // 跳转链接
            {
                innerCardData: JSON.stringify({
                    title: pageTitle,
                    bgUrl: pageHeaderImage,
                    desc: pageSubtitle,
                    jumpUrl: `Kumianmei://home/web?urlType=2&windowType=FULL_MODE&url=${window.location.origin}/movies-tribe?id=${id}`,
                }),
            },
            { pageId: id }
        );
        reportEvent('影视部落', '点击事件', '分享');
    }
    // 点击返回键
    function closeWebView() {
        if (!closeWebview()) {
            if (window.history.state.position > 0) {
                router.go(-1);
            } else {
                router.replace('/');
            }
        }
        reportEvent('影视部落', '点击事件', '关闭当前页');
    }
    // 获取客户端传递数据
    const getAppData = (shareId: any) => {
        if (shareId && shareId !== 'null') {
            getShareData(shareId).then((res) => {
                const { h5Data, redirectUrl = '' } = res;
                const pageId = JSON.parse(h5Data)?.pageId || '';
                console.log(h5Data, 'h5Data');
                sharePageId.value = pageId;
                console.log(sharePageId.value, 'sharePageId');
                getPageData(pageId);
                redirectUrl.value = redirectUrl;
                reportEvent('影视部落', '进入首页', '分享页');
            });
        }
    };

    function handleBack() {
        const data = {
            type: 'CHANGE_HEIGHT',
            height: container.value.offsetHeight,
        };
        // 传参
        window.parent.postMessage(data, '*');
    }

    onMounted(() => {
        reportEvent('影视部落', '首页', '进入首页获取数据');
        // 显示外层按钮
        const data = {
            type: 'SHOW_BTN',
        };
        window.parent.postMessage(data, '*');
        // 判断是否在iframe
        isInIframe.value = window.frames.length !== window.parent.frames.length;
        // 传参
        // handleBack();
        // 分享页面
        if (props.isShare) {
            const shareId = useQuery()?.shareId || '';
            getAppData(shareId);
            return;
        }
        pageData.id = useQuery()?.id || '';
        // 根据id拿到数据 - ajax请求
        if (!pageData.id) {
            return;
        }
        getPageData(pageData.id);
    });
</script>
<style lang="scss" scoped>
    .moviesTribe {
        background: #000;
    }
    .banner_container {
        position: relative;
        width: 750px;
        height: 480px;
        .banner,
        .mask {
            position: absolute;
            width: 100%;
            height: 100%;
        }
        .banner {
            z-index: 1;

            .loading_bg {
                width: 750px;
                height: 480px;
                background: #000;
                color: #fff;
                font-size: 56px;
            }
        }
        .mask {
            padding: 108px 40px;
            z-index: 2;
            background: linear-gradient(180.03deg, rgba(0, 0, 0, 0) 0.02%, #000000 99.98%);

            .top_icon {
                margin-bottom: 46 * 2px;
            }

            .title {
                position: relative;
                font-style: normal;
                font-weight: 700;
                font-size: 56px;
                line-height: 68px;
                color: rgba(255, 255, 255, 0.9);
                .mark {
                    height: 30px;
                    color: rgba(255, 255, 255, 0.9);
                    &.right_mark {
                        position: absolute;
                        right: 0px;
                        bottom: 18px;
                    }
                }

                .title_text {
                    width: 622px;
                    @include lineClamp(2);
                }
            }

            .pageSubtitle {
                margin-top: 16px;
                font-style: normal;
                font-weight: 400;
                font-size: 32px;
                line-height: 40px;
                color: rgba(255, 255, 255, 0.4);
                @include lineClamp(2);
            }
        }
    }

    .section_container {
        margin-bottom: 20px;
        padding: 24px 40px 0px;
        width: 750px;
    }

    .more_recommend {
        margin: 30px 0;
        width: 670px;
        height: 48px;
        font-style: normal;
        font-weight: 700;
        font-size: 40px;
        line-height: 24px;
        color: rgba(255, 255, 255, 0.9);
    }

    .history_container {
        margin-bottom: 40px;
        padding: 0px 30px 110px;
        width: 750px;
    }

    .jump_btn {
        position: fixed;
        bottom: 34px;
        z-index: 99;
        width: 670px;
        height: 104px;
        font-weight: 600;
        font-size: 26px;
        text-align: center;
        color: rgba(0, 0, 0, 0.9);
        background: #ffffff;
        border-radius: 100px;
    }
</style>

<style>
    body {
        background-color: #000;
    }
</style>
